package controller;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.StringTokenizer;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import models.Domain;
import models.Inlink;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;

@SuppressWarnings("serial")
public class InlinkServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		
		resp.setCharacterEncoding("utf-8");
		String path = ((HttpServletRequest)req).getRequestURI();
		
		StringTokenizer st = new StringTokenizer( path,"/");
        int count = st.countTokens(); 
        String page = "1";
        st.nextToken();
		String domainName = st.nextToken();
		
		domainName=Utils.fomatDomain(domainName);
		
		if(Utils.checkDomain(domainName))
		{
	        if(count != 2 && count != 3)
	        {
	        	try {
					req.getRequestDispatcher("/404error.jsp").forward(req, resp);
				} catch (Exception e) {
					e.printStackTrace();
				}
	        	return ;
	        }
			if(count == 3)
			{
				page = st.nextToken();
			}
		
			for (int i = 0; i < page.length(); i++) {
				 if ((page.charAt(i) >= 'A' && page.charAt(i) <= 'Z') || (page.charAt(i) >= 'a' && page.charAt(i) <= 'z')) {
					 resp.sendRedirect("/");
		             break;
		         }
	        }
			
			try {
				ObjectifyService.register(Inlink.class);
			} catch (Exception e) {
				// TODO: handle exception
			}
			Objectify objectify = ObjectifyService.begin();
			try {
				Inlink domain = objectify.get(new Key<Inlink>(Inlink.class, domainName));
	
				resp.setHeader( "Cache-Control", "public, max-age=86400");
				resp.setHeader( "Expires", new Date(Calendar.getInstance().getTime().getTime()+24*60*60*1000).toGMTString());
				
				req.setAttribute("list", domain);
				
			} catch (Exception e) {
				
			}
			req.setAttribute("domain", domainName);
			req.setAttribute("page", page);
			try {
				req.getRequestDispatcher("/in-link.jsp").forward(req, resp);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			try {
				req.getRequestDispatcher("/404error.jsp").forward(req, resp);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}
